﻿import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tencent_cloud_chat_sdk/enum/V2TimAdvancedMsgListener.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:vischat/core/utils/tencent/message_util.dart';

class ChatController extends GetxController {
  final _isLoading = false.obs;
  final _newMessageCount = 0.obs;

  final _refreshController = EasyRefreshController();
  final _scrollController = ScrollController();

  late V2TimConversation conversation;
  String? _lastMsgID;

  final messages = <V2TimMessage>[].obs;

  get refreshController => _refreshController;
  get scrollController => _scrollController;
  get isLoading => _isLoading.value;
  get newMessageCount => _newMessageCount.value;

  @override
  onInit() {
    super.onInit();
    conversation = Get.arguments['conversation'];
    MessageUtil.markMessagesRead(conversation);
    loadMessages();
    _setupMessageListener();
  }

  void jumpToLatest() {
    if (messages.isEmpty) return;

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _scrollController.animateTo(
        0,
        duration: Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
      _newMessageCount.value = 0;
    });
  }

  Future<void> loadMessages() async {
    if (_isLoading.value) return;

    _isLoading.value = true;

    try {
      final result = await MessageUtil.getMessageList(
        userID: conversation.userID ?? '',
        lastMsgID: _lastMsgID,
      );
      if (result != null) {
        if (_lastMsgID == null) {
          messages.assignAll(result); // 初始加载
        } else {
          messages.insertAll(0, result); // 加载更多
        }
        _updateLastMsgID();
      }
    } finally {
      _isLoading.value = false;
    }
  }

  void addReceivedMessage(V2TimMessage msg) {
    MessageUtil.markMessagesRead(conversation);
    messages.insert(0, msg);
  }

  void _updateLastMsgID() {
    if (messages.isNotEmpty) {
      _lastMsgID = messages.first.msgID;
    }
  }

  void _setupMessageListener() {
    MessageUtil.addAdvancedMsgListener(
      V2TimAdvancedMsgListener(
        onRecvNewMessage: (msg) {
          addReceivedMessage(msg);
        },
      ),
    );
  }

  @override
  void onClose() {
    _refreshController.dispose();
    _scrollController.dispose();
    MessageUtil.removeAdvancedMsgListener();
    super.onClose();
  }
}
